import DataBus, {centerRouteVenue, leftRouteVenue, rightRouteVenue} from "../../databus";
import Utils from "../../common/utils";
import {PageStatus} from "../../page_status";
import XmlManager from "../../manager/xml_manager";
import Scene from "../../runtime/scene";
import Text from "../../base/text";

const databus = new DataBus()
const xmlManager = new XmlManager()
const btnImg = new Image()
import {winW, winH, px, px2rem} from '../../libs/utils.js';
import Scroller from "../../base/scroller";
import {Circle, CircleText, Rect} from "../../base/shape";
import Img from "../../base/img";
import ImgAnim from "../../base/image_anim";
import ImgText from "../../base/img_text";
import AlbumView from "../../runtime/album";
import Block from "../../base/block";
import JsLogic from "../../runtime/jslogic";

const anchor = 0;
const innerScrollerRight = 316 + 1440 + 1440 + 1440;/// 4636
var jsLogic = new JsLogic();
/// 下标 名称 坐标x 坐标Y
const eastVenueIndex = new Map([
    [0, ["三沙", px(270), px(innerScrollerRight - 250)]],
    [1, ["海南", px(400), px(innerScrollerRight - 500)]],
    [2, ["广东", px(350), px(innerScrollerRight - 750)]],
    [3, ["澳门", px(160), px(innerScrollerRight - 1000)]],
    [4, ["香港", px(350), px(innerScrollerRight - 1250)]],
    [5, ["台湾", px(390), px(innerScrollerRight - 1500)]],
    [6, ["福建", px(200), px(innerScrollerRight - 1750)]],
    [7, ["浙江", px(280), px(innerScrollerRight - 2050)]],
    [8, ["上海", px(420), px(innerScrollerRight - 2300)]],
    [9, ["江苏", px(290), px(innerScrollerRight - 2600)]],
    [10, ["山东", px(280), px(innerScrollerRight - 2950)]],
    [11, ["天津", px(230), px(innerScrollerRight - 3300)]],
    [12, ["辽宁", px(150), px(innerScrollerRight - 3550)]],
    [13, ["吉林", px(330), px(innerScrollerRight - 3800)]],
    [14, ["黑龙江", px(440), px(innerScrollerRight - 4100)]],
    [1000, ["漠河", px(260), px(innerScrollerRight - 4350)]],
]);
const postCardMap = new Map();

/**
 * 旅行显示页 ui
 */
export default class TripShow extends Scene {
    constructor() {
        super(0, 0, winW, winH);
        this.albumView = null;
        this.passingPids = [];
        this.currentPid = 0;
        this.chargeDialog = null;
        this.chargeNumber = 500;
        this.userWalletText = null;
        this.catWalletText = null;
    }

    initView(ctx) {
        setTimeout(() => {
            this.initData()
            switch (jsLogic.line.toLowerCase()) {
                case "left":
                    this.initLeftRoute(ctx);
                    break;
                case "center":
                    this.initCenterRoute(ctx);
                    break;
                default:
                    this.initRightRoute(ctx);
                    break;
            }
            this.initMenu(ctx);
            this.addDebugView()


            if(jsLogic.getTravelType() === "Play"){

                var postCards = postCardMap.get(this.currentPid);
                if (this.albumView !== null && this.albumView.visible === true) {
                    return;
                }
                var imgList = []
                postCards.forEach(value => {
                    imgList.push(`js/sub/images/postcard/r_${this.currentPid}_${value}_0.png`,)
                })
                if(imgList.length > 0){
                    this.showAlbumView(imgList);
                    setTimeout(() => {
                        wx.showToast({
                            title: `猫咪到了${jsLogic.getCurSidName()}，这是寄过来的明信片`,icon:'none'
                        });
                    },1000)

                }

            }else {
                setTimeout(() => {
                    wx.showToast({
                        title: `猫咪在路途中`,icon:'none'
                    });
                },1000)

            }



        }, 0);

    }

    initData() {
        if (jsLogic.bInitDone !== true) {
            // debugger
            return;
        }
        /// 已经玩过的省份
        this.passingPids = jsLogic.getPassingPids();
        ///当前省份地点id
        this.currentPid = jsLogic.getCurrentPid();
        this.passingPids.forEach(value => {

            var playedIdsByPid = jsLogic.getPlayedIdsByPid(value);
            console.log(`当前玩的省份 ${value} 景点: ${playedIdsByPid}`)
            postCardMap.set(value, playedIdsByPid);
        })


    }

    initMenu(ctx) {
        /** 按钮 主界面/打钱: **/
        var btnToMain = new Img("js/sub/images/btn_zhuye.png", 0, winH - 20 - px(132), px(210), px(132), px(210), (132));
        btnToMain.bindClickEvent(() => {
            if (this.albumView !== null && this.albumView.visible === true) {
                return;
            }
            databus.gameStatus = PageStatus.GameMainMenu;
            wx.setStorage({
                key: "lastPage",
                data: PageStatus.GameMainMenu
            })
        });
        this.addChild(btnToMain, "btnToMain")

        var btnCharge = new Img("js/sub/images/btn_daqian.png", winW - 30 - px(156), winH - 20 - px(142), px(156), px(142), px(156), px(142));
        this.addChild(btnCharge, "btnCharge")
        btnCharge.bindClickEvent(() => {
            if (this.albumView !== null && this.albumView.visible === true) {
                return;
            }
            this.addChargeDialog(ctx)
        });
        /// 玩家钱包
        var imgUserWalletBg = new Img("js/sub/images/img_wjcy_db.png", winW - px(266) - 20, px(155), px(266), px(60), px(266), (60));
        this.addChild(imgUserWalletBg, "imgUserWalletBg")

        var imgUserWalletFish = new Img("js/sub/images/icon_yugan.png", winW - px(266) - 30, px(160), px(62), px(48), px(62), (48));
        this.addChild(imgUserWalletFish, "imgUserWalletFish")

        //// 猫咪状态
        var imgCatWalletBg = new Img("js/sub/images/img_fy_db.png", 0, px(150), px(312), px(76), px(312), (76));
        this.addChild(imgCatWalletBg, "imgCatWalletBg")
        //// 猫咪没钱的状态
        var imgCat = new Img("js/sub/images/img_fuyu_gao.png", 20, px(155), px(92), px(64), px(92), (64));
        this.addChild(imgCat, "imgCat")

        const promise = new Promise((resolve, reject) => {
            // 1 秒后执行 resolve 方法
            setTimeout(() => {
                resolve(jsLogic.info.show.cur_el_name);
            }, 100);
        });


        // 使用 then 方法处理 Promise 对象的结果
        promise.then(result => {
            console.log(result); // 输出 "1 秒后执行"
            this.catWalletText = new Text(jsLogic.info.show.cur_el_name, px(92) + 30, px(170), px(30))
            this.addChild(this.catWalletText, "catWalletText")

            this.userWalletText = new Text(`玩家持有: ${jsLogic.info.base.user_money}`, winW - px(266 - 62) - 30, px(170), px(28))
            this.addChild(this.userWalletText, "userWalletText")

        });
    }

    initLeftRoute(ctx) {
    }

    initCenterRoute(ctx) {
        var scroller = new Scroller(0, 100, winW, winH - 150);
        scroller.bgColor = 'lightBlue'; //lightBlue


        var img1 = new Img("js/sub/images/img_dong_board.png", 0, 0, winW, winH);
        scroller.addChild(img1, "img1")
        var img2 = new Img("js/sub/images/img_dong_board.png", 0, winH, winW, winH);
        scroller.addChild(img2, "img2")

        // var greenRec = new View(40, 0, 40, winH*2);
        // greenRec.bgColor = 'green';
        // greenRec.boxSizing = 'padding-box';
        // greenRec.border = '5px solid black';

        // var rect = new Rect(150, 250, 100, 40, 10);
        // rect.bgColor = 'red';
        // var circle = new Circle(150, 300, 40);
        // circle.bgColor = '#000';


        var circleText = new CircleText(150, winH * 2 - 200, 40, "三亚");
        circleText.bgColor = '#E3D768FF';
        circleText.border = '2px solid gray';
        circleText.bindClickEvent(() => {
            if (this.albumView !== null && this.albumView.visible === true) {
                return;
            }
            var imgList = ["js/sub/images/postcard/r_1_1_0.png",
                "js/sub/images/postcard/r_1_2_0.png",
                "js/sub/images/postcard/r_1_3_0.png",
                "js/sub/images/postcard/r_1_4_0.png",
                "js/sub/images/postcard/r_1_5_0.png",
                "js/sub/images/postcard/r_1_6_0.png",
                "js/sub/images/postcard/r_1_7_0.png",
                "js/sub/images/postcard/r_1_8_0.png",
                "js/sub/images/postcard/r_1_9_0.png",
                "js/sub/images/postcard/r_1_10_0.png",
                "js/sub/images/postcard/r_1_11_0.png",
                "js/sub/images/postcard/r_1_12_0.png"]
            this.showAlbumView(imgList);
            // wx.showToast({
            //     title: '准备出发～',
            // });
        });

        var circleText2 = new ImgText('js/sub/images/btn_guanqia.png', 200, winH * 2 - 400, 70, 60, 70, 60, "鼓浪屿");
        // var circleText2 = new CircleText(200, winH*2-400, 40,"鼓浪屿");
        // circleText2.bgColor = '#E3D768FF';
        // circleText2.border = '2px solid gray';
        circleText2.bindClickEvent(() => {
            if (this.albumView !== null && this.albumView.visible === true) {
                return;
            }
            var imgList = [
                "js/sub/images/postcard/r_2_13_0.png",
                "js/sub/images/postcard/r_2_14_0.png",
                "js/sub/images/postcard/r_2_15_0.png",
                "js/sub/images/postcard/r_2_16_0.png",
                "js/sub/images/postcard/r_2_17_0.png",
                "js/sub/images/postcard/r_2_18_0.png",
                "js/sub/images/postcard/r_2_19_0.png"]
            this.showAlbumView(imgList);

        });


        var circleText3 = new ImgText('js/sub/images/btn_guanqia.png', 220, winH * 2 - 600, 70, 60, 70, 60, "上海");
        // var circleText3 = new CircleText(150, winH*2-600, 40,"上海");
        // circleText3.bgColor = '#E3D768FF';
        // circleText3.border = '2px solid gray';


        var circleText4 = new ImgText('js/sub/images/btn_guanqia.png', 200, winH * 2 - 800, 70, 60, 70, 60, "江苏");
        // var circleText4 = new CircleText(200, winH*2-800, 40,"江苏");
        // circleText4.bgColor = '#E3D768FF';
        // circleText4.border = '2px solid gray';

        var circleText5 = new ImgText('js/sub/images/btn_guanqia.png', 200, winH * 2 - 1000, 70, 60, 70, 60, "山东");
        // var circleText5 = new CircleText(150, winH*2-1000, 40,"山东");
        // circleText5.bgColor = '#E3D768FF';
        // circleText5.border = '2px solid gray';

        var circleText6 = new ImgText('js/sub/images/btn_guanqia.png', 200, winH * 2 - 1200, 70, 60, 70, 60, "北京");
        // var circleText6 = new CircleText(200, winH*2-1200, 40,"北京");
        // circleText6.bgColor = '#E3D768FF';
        // circleText6.border = '2px solid gray';

        // var circleText7 = new CircleText(150, winH*2-1400, 40,"哈尔滨");
        var circleText7 = new ImgText('js/sub/images/btn_guanqia.png', 200, winH * 2 - 1400, 70, 60, 70, 60, "哈尔滨");
        // circleText7.bgColor = '#E3D768FF';
        // circleText7.border = '2px solid gray';

        var circleText8 = new ImgText('js/sub/images/btn_guanqia.png', 180, 100, 70, 60, 70, 60, "漠河");
        // circleText8.bgColor = '#E3D768FF';
        // circleText8.border = '2px solid gray';
        // var circleText8 = new Img('images/btn_guanqia.png',150, 100, 100,100);
        // circleText8.bgColor = '#E3D768FF';
        // circleText8.border = '2px solid gray';

        circleText8.bindClickEvent(() => {
            if (this.albumView !== null && this.albumView.visible === true) {
                return;
            }
            var imgList = [
                "js/sub/images/postcard/r_2_13_0.png",
                "js/sub/images/postcard/r_2_14_0.png",
                "js/sub/images/postcard/r_2_15_0.png",
                "js/sub/images/postcard/r_2_16_0.png",
                "js/sub/images/postcard/r_2_17_0.png",
                "js/sub/images/postcard/r_2_18_0.png",
                "js/sub/images/postcard/r_2_19_0.png"]
            this.showAlbumView(imgList);
            // wx.showToast({
            //     title: '准备展示相册',
            // });
        });

        // scroller.addChild(greenRec, 'a');
        // scroller.addChild(rect, 'rect');
        // scroller.addChild(circle, 'circle');
        scroller.addChild(circleText, 'circleText');
        scroller.addChild(circleText2, 'circleText2');
        scroller.addChild(circleText3, 'circleText3');
        scroller.addChild(circleText4, 'circleText4');
        scroller.addChild(circleText5, 'circleText5');
        scroller.addChild(circleText6, 'circleText6');
        scroller.addChild(circleText7, 'circleText7');
        scroller.addChild(circleText8, 'circleText8');

        let catAnim = new ImgAnim('js/sub/images/wa', 12, 205, 1500, 103, 104);
        scroller.addChild(catAnim, "catAnim")


        scroller.initChildChange();
        this.addChild(scroller, 'scroller');

        scroller.scrollToBottom();

        var backImg = new Img("js/sub/images/icon_back.png", 10, 20, 40, 40);
        backImg.bindClickEvent(() => {
            if (this.albumView !== null && this.albumView.visible === true) {
                return;
            }
            databus.gameStatus = PageStatus.GameMainMenu;
        });
        this.addChild(backImg, 'backImg')
    }

    initRightRoute(ctx) {

        var scroller = new Scroller(0, 0, winW, winH);
        scroller.bgColor = 'pink'; //lightBlue

        /** 背景图 start **/
        var img4 = new Img("js/sub/images/bg/img_dong_bg04.png", 0, 0, px(640), px(316));
        scroller.addChild(img4, "img4")
        var img3 = new Img("js/sub/images/bg/img_dong_bg03.png", 0, px(316), px(640), px(1440));
        scroller.addChild(img3, "img3")
        var img2 = new Img("js/sub/images/bg/img_dong_bg02.png", 0, px(316) + px(1440), px(640), px(1440));
        scroller.addChild(img2, "img2")
        var img1 = new Img("js/sub/images/bg/img_dong_bg01.png", 0, px(316 + 1440 + 1440), px(640), px(1440));
        scroller.addChild(img1, "img1")
        /** 背景图 end **/

        /** 按钮地点 start**/
        eastVenueIndex.forEach((values, keyId) => {
            console.log(keyId, values); // 输出每个键和对应的值（数组）
            let includes = this.passingPids.includes(keyId);
            var btnVenue = new ImgText(includes ? 'js/sub/images/btn_unlock.png' : 'js/sub/images/btn_lock.png', values[1], values[2], px(86), px(66), px(86), px(66), values[0], "center", includes ? "#e5883c" : "#8a8a8a");
            scroller.addChild(btnVenue, `btnVenue${keyId}`)
            btnVenue.bindClickEvent(() => {
                if (this.chargeDialog !== null && this.chargeDialog.visible === true) {
                    return;
                }

                var postCards = postCardMap.get(keyId);
                if (includes === true && typeof postCards !== "undefined" && postCards.length > 0) {
                    if (this.albumView !== null && this.albumView.visible === true) {
                        return;
                    }
                    var imgList = []
                    postCards.forEach(value => {
                        imgList.push(`js/sub/images/postcard/r_${keyId}_${value}_0.png`,)
                    })
                    this.showAlbumView(imgList);

                } else {
                    wx.showToast({
                        title: '还没有收到猫咪的明信片', icon: 'none',
                    });
                }
            });
        });

        /** 青蛙帧动画 **/
        var currentElement = eastVenueIndex.get(this.currentPid);
        let catAnim = new ImgAnim('js/sub/images/wa', 12, 205, currentElement[2] - 60, 103, 104);
        scroller.addChild(catAnim, "catAnim")

        scroller.initChildChange();
        this.addChild(scroller, 'scroller');

        /// 从底部开始滚动到上面到距离
        scroller.scrollToPoint(px(innerScrollerRight) - currentElement[2] + winH / 2);


    }

    update() {
        super.update();
        if (databus.gameStatus !== PageStatus.TripShow) {
            return;
        }


    }

    render(ctx) {
        if (databus.gameStatus !== PageStatus.TripShow) {
            return;
        }
        super.render(ctx);
    }

    showAlbumView(imgList) {

        if (this.albumView == null) {
            this.albumView = new AlbumView(0, 0, winW, winH, imgList)
            this.albumView.setCallback(() => {
                this.hideAlbumView();
            });
            this.albumView.bgColor = 'rgba(0,0,0,0.5)';
            this.addChild(this.albumView, "albumView")
        } else {
            // debugger
            this.albumView.setImgList(imgList)
            this.albumView.visible = true;
        }

    }

    hideAlbumView() {
        // debugger
        this.albumView.visible = false;
    }

    onTouchEvent(type, x, y, callback) {

        switch (type) {
            case 'touchstart':
                break
        }
    }

    addChargeDialog(ctx) {
        if (this.chargeDialog !== null) {
            return
        }
        var dialog = new Block(20, winH / 2 - 40, winW - 40, 60);
        this.chargeDialog = dialog;


        var rect = new Rect(20, winH / 2 - 40, winW - 40, 60, 10);
        rect.bgColor = 'white';

        var img1 = new Img("js/sub/images/icon_add.webp", 40, winH / 2 - 30, 40, 40);
        var img2 = new Img("js/sub/images/icon_subtract.webp", 140, winH / 2 - 30, 40, 40);
        var text = new Text(this.chargeNumber, 90, winH / 2 - 20, 20);
        var sendText = new Text("发送金额", winW - 150, winH / 2 - 20, 20);
        sendText.bgColor = 'lightBlue';
        this.addChild(dialog, "dialog")
        dialog.addChild(rect, "rect")
        dialog.addChild(img1, "img1")
        dialog.addChild(img2, "img2")
        dialog.addChild(text, "text")
        dialog.addChild(sendText, "sendText")
        this.drawToCanvas(ctx)


        img1.bindClickEvent(() => {
            this.chargeNumber += 500;
            text.text = this.chargeNumber;
        })
        img2.bindClickEvent(() => {
            this.chargeNumber -= 500;
            if (this.chargeNumber <= 0) {
                this.chargeNumber = 0;
            }
            text.text = this.chargeNumber;
        })

        sendText.bindClickEvent(() => {
            if (this.chargeNumber > jsLogic.info.base.user_money) {
                this.hideChargeDialog();
                wx.showToast({
                    title: `余额不足 去玩一局跳棋赚取小鱼干吧`, icon: "none"
                });
                return;
            }
            wx.showToast({
                title: `充值金额 ${this.chargeNumber}`,
            });
            jsLogic.giveMoneyToCat(this.chargeNumber)
            this.userWalletText.text = `玩家持有: ${jsLogic.info.base.user_money}`;
            this.catWalletText.text = `${jsLogic.info.show.cur_el_name}`;
            this.hideChargeDialog();
        })
    }

    hideChargeDialog() {
        if (this.chargeDialog !== null) {
            this.removeChild(this.chargeDialog)
            this.chargeDialog = null;
            this.chargeNumber = 500;
        }

    }

    emptyChild() {
        super.emptyChild();
        this.albumView = null;
        this.chargeDialog = null;
    }
}
